<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Models\AdminUser as User;
use App\Models\Term;


class TermController extends Controller
{
    protected $fields = [
        'station_type' => 1,
        'device_type' => 0,
        'area_config' => 0,
        'area_list' => '',
        'channel' => '',
        'source' => '',
        'ips' => '',
        'delivery_time' => '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23',
        'status' => 1,
        'aid' => 0,
		'name'=>''
    ];

    public function __construct(Request $request)
    {
        /*   $this->uid = auth()->user()->id;
          $condition = [['wechats.uid', '>', 0],];
          if($this->uid > 1){
              $condition = array('wechats.uid'=>$this->uid);

          }
          $this->condition = $condition; */
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = array();
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
            $data['recordsTotal'] = Term::where('aid',0)->orWhere('aid',auth()->user()->id)->count();
            if (strlen($search['value']) > 0) {
				$data['recordsFiltered'] = Term::where(function ($query){
						$query->where('aid',0)->orWhere('aid',auth()->user()->id);
					})->where(function ($query) use ($search) {
						$query->where('wx_num', 'LIKE', '%' . $search['value'] . '%')
							->orWhere('wx_nike', 'like', '%' . $search['value'] . '%')
							->orWhere('wechat_groups.name', 'like', '%' . $search['value'] . '%');
					})->count();

                $data['data'] = Term::where(function ($query){
						$query->where('aid',0)->orWhere('aid',auth()->user()->id);
					})->where(function ($query) use ($search) {
                        $query->where('wx_num', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('wx_nike', 'like', '%' . $search['value'] . '%')
                            ->orWhere('wechat_groups.name', 'like', '%' . $search['value'] . '%');
                    })
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                $data['recordsFiltered'] = $data['recordsTotal'];
                $data['data'] = Term::where('aid',0)->orWhere('aid',auth()->user()->id)
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);
        }
		$data['station_type'] = config("app.station_type");
		$data['allow_channel'] = config("app.allow_channel");
		$data['device_type'] = config("app.device_type");
		$data['area_config'] = config("app.area_config");
        return view('admin.term.index',$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
		
		$data['delivery_times'] = config('app.delivery_time');
		$data['delivery_value'] = config('app.delivery_time');
        return view('admin.term.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    { 
        if(empty($request->get('name')))  return redirect()->back()->withErrors("条件名不能为空！");
        $tag = new Term();
        foreach (array_keys($this->fields) as $field) {
            if ($field == 'aid') {
                $tag->$field = auth()->user()->id;
				continue;
            }if($field=='status'){
				 $tag->$field = $request->get($field)>=1?$request->get($field):0;
				 continue;
			}
			if($field == 'ips'){
                $ips = explode("\n",$request->ips);
				$ipss=[];
				foreach($ips as $ip){
					if(trim($ip)!='') $ipss[] = trim($ip);
				}
				$tag->$field = json_encode($ipss);
				continue;
            }
			if($field == 'area_list' && $tag->area_config != 0){
                $tag->$field = join(',',$request->get($field));
				continue;
            }
            $tag->$field = $request->get($field);
			
        }
		$tag->save();
		return redirect('/admin/term')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $tag = Term::find((int)$id);
        if (!$tag) return redirect('/admin/term')->withErrors("找不到该条件!");
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $tag->$field);
        }
		if($data['area_config']){
            $area_list = explode(',',$data['area_list']);
            $strArea = "";
            foreach ($area_list as $key => $obj){
                $itemArr = explode('-',$obj);
                if($key > 0) $strArea .=',';
                $strArea .= '{"code":'.$itemArr[0].',"name":"'.$itemArr[1].'"}';
            }
            $data['area_list'] =$strArea;
        }
		if($data['ips']=='[]'){
           $data['ips']='';
        }
		$data['id'] = $id;
		$data['delivery_times']=config('app.delivery_time');
		$delivery_value = explode(',',$tag->delivery_time);
		$data['delivery_value']=[];
		foreach($delivery_value as $dv){
			$data['delivery_value'][$dv] = $dv;
		}
        return view('admin.term.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    { 
        $this->validate($request, ['name' => 'required|unique:group_template_term,name,' . $id]);
        $tag = Term::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
            if ($field == 'aid') {
                continue;
            }
			if($field=='status'){
				 $tag->$field = $request->get($field)>=1?$request->get($field):0;
				 continue;
			}
			if($field == 'ips'){
                $ips = explode("\n",$request->ips);
				$ipss=[];
				foreach($ips as $ip){
					if(trim($ip)!='') $ipss[] = trim($ip);
				}
				$tag->$field = json_encode($ipss);
				continue;
            }
			if($field == 'area_list' && $tag->area_config != 0){
                $tag->$field = join(',',$request->get($field));
				continue;
            }
            $tag->$field = $request->get($field);
        }
		
        $tag->save();
        return redirect('/admin/term')->withSuccess('更新成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (is_numeric($id)) {
            $tag = Term::find((int)$id);
            if ($tag) {
                $tag->delete();
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        } else {
            $idArr = explode(',', $id);
            $recordRow = Term::whereIn('id', $idArr)->delete();
            if (!$recordRow) {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }
        return redirect()->back()
            ->withSuccess("删除成功");
    }

}